<template>
  <div class="user-detail">
    <div class="page-header">
      <h1>用户详情</h1>
      <div class="header-actions">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑用户
        </el-button>
        <el-button 
          v-if="user.is_active" 
          type="warning" 
          @click="handleDeactivate"
        >
          <el-icon><Lock /></el-icon>
          禁用用户
        </el-button>
        <el-button 
          v-else 
          type="success" 
          @click="handleActivate"
        >
          <el-icon><Unlock /></el-icon>
          启用用户
        </el-button>
        <el-button type="info" @click="handleResetPassword">
          <el-icon><Key /></el-icon>
          重置密码
        </el-button>
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          删除用户
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ user.full_name }}</el-descriptions-item>
            <el-descriptions-item label="角色">
              <el-tag :type="getRoleType(user.role)">
                {{ getRoleText(user.role) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="user.is_active ? 'success' : 'danger'">
                {{ user.is_active ? '活跃' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(user.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="最后登录">{{ formatDateTime(user.last_login) || '从未登录' }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatDateTime(user.updated_at) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card style="margin-top: 20px;" v-if="user.role === 'student'">
          <template #header>
            <div class="card-header">
              <span>学生信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="学号">{{ user.student_id || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="班级">{{ user.class_name || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="年级">{{ user.grade || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{ user.major || '未设置' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card style="margin-top: 20px;" v-if="user.role === 'teacher'">
          <template #header>
            <div class="card-header">
              <span>教师信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工号">{{ user.teacher_id || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ user.department || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="职称">{{ user.title || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="入职时间">{{ formatDate(user.hire_date) || '未设置' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button 
              type="primary" 
              size="large" 
              @click="handleEdit"
              style="width: 100%; margin-bottom: 10px;"
            >
              <el-icon><Edit /></el-icon>
              编辑用户
            </el-button>
            <el-button 
              type="warning" 
              size="large" 
              @click="handleResetPassword"
              style="width: 100%; margin-bottom: 10px;"
            >
              <el-icon><Key /></el-icon>
              重置密码
            </el-button>
            <el-button 
              v-if="user.role === 'student'"
              type="success" 
              size="large" 
              @click="$router.push(`/scores?user_id=${user.id}`)"
              style="width: 100%;"
            >
              <el-icon><TrendCharts /></el-icon>
              查看成绩
            </el-button>
          </div>
        </el-card>

        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>用户统计</span>
            </div>
          </template>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-label">注册天数</div>
              <div class="stat-value">{{ getDaysSinceCreation() }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">登录次数</div>
              <div class="stat-value">{{ user.login_count || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">账户状态</div>
              <div class="stat-value">
                <el-tag :type="user.is_active ? 'success' : 'danger'" size="small">
                  {{ user.is_active ? '正常' : '禁用' }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '../api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Lock, Unlock, Key, Delete, TrendCharts } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const user = ref({});

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN');
};

const formatDate = (date) => {
  if (!date) return null;
  return new Date(date).toLocaleDateString('zh-CN');
};

const getRoleType = (role) => {
  const roleMap = {
    'admin': 'danger',
    'teacher': 'warning',
    'student': 'success'
  };
  return roleMap[role] || 'info';
};

const getRoleText = (role) => {
  const roleMap = {
    'admin': '管理员',
    'teacher': '教师',
    'student': '学生'
  };
  return roleMap[role] || '未知';
};

const getDaysSinceCreation = () => {
  if (!user.value.created_at) return 0;
  const created = new Date(user.value.created_at);
  const now = new Date();
  const diffTime = Math.abs(now - created);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
};

const loadUser = async () => {
  try {
    const response = await api.users.getUser(route.params.id);
    user.value = response.data;
  } catch (error) {
    ElMessage.error('加载用户详情失败');
  }
};

const handleEdit = () => {
  ElMessage.info('编辑功能开发中...');
};

const handleActivate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要启用用户"${user.value.username}"吗？`,
      '启用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await api.users.activateUser(user.value.id);
    ElMessage.success('用户启用成功');
    loadUser();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('启用用户失败');
    }
  }
};

const handleDeactivate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用用户"${user.value.username}"吗？`,
      '禁用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await api.users.deactivateUser(user.value.id);
    ElMessage.success('用户禁用成功');
    loadUser();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('禁用用户失败');
    }
  }
};

const handleResetPassword = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户"${user.value.username}"的密码吗？`,
      '重置密码确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await api.users.resetPassword(user.value.id);
    ElMessage.success('密码重置成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置密码失败');
    }
  }
};

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${user.value.username}"吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await api.users.deleteUser(user.value.id);
    ElMessage.success('用户删除成功');
    router.push('/users');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败');
    }
  }
};

onMounted(() => {
  loadUser();
});
</script>

<style scoped>
.user-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.user-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
</style>